<?php

namespace Dcat\Admin\Grid\Displayers;

abstract class Editable extends AbstractDisplayer
{
    protected $type;

    protected $view;

    protected $options = [
        // 是否刷新页面
        'refresh' => false,
    ];


    protected $url = '';

    public function display($options = [], $urlData=[])
    {
        if (is_bool($options)) {
            $options = ['refresh' => $options];
        }

        $this->options = array_merge($this->options, $options);

        foreach ($this->options as $optionName => $option)
        {
            if($optionName == 'url')
            {
                $this->url = $option;

                unset($this->options['url']);
            }
        }

        if(!empty($urlData))
            $this->setUrlData($urlData);



        return admin_view($this->view, array_merge($this->variables(), $this->defaultOptions() + $this->options));
    }

    protected function defaultOptions()
    {
        return [];
    }

    public function variables()
    {
        return [
            'key'     => $this->getKey(),
            'class'   => $this->getSelector(),
            'name'    => $this->getName(),
            'type'    => $this->type,
            'display' => $this->getValue(),
            'value'   => $this->getOriginal(),
            'url'     => $this->getUrl(),
        ];
    }


    public function setUrlData($urlData = [])
    {
        if(empty($urlData))
            return '';


        $url = $this->getUrl();

        $urlDataArr = [];

        foreach ($urlData as $urlDataName)
        {
            if(isset($this->row->$urlDataName))
                $urlDataArr[] = $urlDataName .'='.$this->row->$urlDataName ?? '';
        }

        $urlDataStr = implode('&', $urlDataArr);

        $this->url = $url .'?'.$urlDataStr;


    }

    protected function getName()
    {
        return $this->column->getName();
    }

    protected function getValue()
    {
        return $this->value;
    }

    protected function getOriginal()
    {
        return $this->column->getOriginal();
    }

    protected function getSelector()
    {
        return 'grid-editable-'.$this->type;
    }

    protected function getUrl()
    {

        if(empty($this->url))
            return $this->resource().'/'.$this->getKey();

        return $this->url;
    }
}
